package com.acme.net;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

import static com.acme.net.Util.echo;
import static com.acme.net.Util.sendMessage;

// TODO [MY] BankClient must be created in new java project (see p.4)
public class BankClient {
    private void run() {
        Socket requestSocket = null;
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        try {
            // 1. creating a socket to connect to the server
            requestSocket = new Socket("localhost", 2012);
            echo("Available commands: -statistics, -add <feed>, bye");
            echo("Connected to localhost in port 2012");
            // 2. get Input and Output streams
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());
            // 3: Communicating with the server
            String message = null;
            BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
            try {
                message = (String) in.readObject();
                echo("server>" + message);
            } catch (ClassNotFoundException e) {
                System.err.println("Data received in unknown format");
            }
            do {
                try {
                    String userCommand = consoleInput.readLine();
                    sendMessage("client>", out, userCommand);
                    message = (String) in.readObject();
                    echo("server>" + message);
                } catch (ClassNotFoundException e) {
                    System.err.println("Data received in unknown format");
                }
            } while (message != null && !message.equals("bye"));
        } catch (UnknownHostException e) {
            System.err.println("You are trying to connect to an unknown host!");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            // 4: Closing connection
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
                if (requestSocket != null) {
                    requestSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {
        new BankClient().run();
    }
}